//
//  SearchCigaretteTableViewController.m
//  FloatClouds
//
//  Created by 黄威 on 16/9/7.
//  Copyright © 2016年 黄威. All rights reserved.
//

#import "SearchCigaretteTableViewController.h"
#import "HWLNetworkTool.h"
#import "NSString+HVV.h"
#import "CigaretteTypeCell.h"
#import "Rank3.h"
#import "RankTableViewThirdCell.h"
#import "UIImageView+WebCache.h"
#import "ProductDetailTableViewController.h"
#import <iflyMSC/iflyMSC.h>
#import "IATConfig.h"
#import "PopupView.h"
#import "IATViewController.h"
#import "SVProgressHUD.h"
@interface SearchCigaretteTableViewController ()<UISearchBarDelegate>

@property (strong, nonatomic)UISearchBar *searchBar;
@property (nonatomic, copy) NSString *searchContect;
@property (nonatomic, strong) NSMutableArray *arrayOfSearchData;
@property (nonatomic, strong) NSMutableArray *arrayOfSearchDataId;
@property (nonatomic, copy) NSString *requestid;
@property (nonatomic, retain) NSMutableArray *arrayOFSearchDetailData;
@property (nonatomic, retain) Rank3 *rank3;
@property (nonatomic, strong) IFlySpeechRecognizer *iFlySpeechRecognizer;//创建识别对象;
@property (nonatomic, strong) UIBarButtonItem *vioceButton;


@end
@implementation SearchCigaretteTableViewController


- (void)viewDidLoad{
  
    self.arrayOfSearchDataId = [NSMutableArray array];
    self.arrayOfSearchData = [NSMutableArray array];
    [self createNavigation];
    [self.tableView registerClass:[CigaretteTypeCell class] forCellReuseIdentifier:@"CigaretteTypeCell"];
    [self.tableView registerClass:[RankTableViewThirdCell class] forCellReuseIdentifier:@"RankTableViewThirdCell"];
    self.searchBar = [[UISearchBar alloc]init];
    self.searchBar.keyboardType = UIKeyboardTypeDefault;
    self.navigationItem.titleView = self.searchBar;
    self.searchBar.delegate = self;
 
}


- (void)createNavigation{
    
    //设置navigation相关属性
    
 
    
    
    self.vioceButton = [[UIBarButtonItem alloc]initWithTitle:@"语音输入" style:UIBarButtonItemStylePlain target:self action:@selector(cancel)];
    
    self.navigationItem.rightBarButtonItem = self.vioceButton;
  
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    
}

- (void)cancel{
    
   
    IATViewController *iat = [[IATViewController alloc]init];
    iat.ReturnVoiceString = ^(NSString *str){
    
        
        
        NSInteger num = str.length - 1;
        
        NSString *searchOfName = [str substringToIndex:num];
        
        self.searchContect = searchOfName;
        
        [self.arrayOfSearchData removeAllObjects];
        
        [self handData];
    
    };
    [self.navigationController pushViewController:iat animated:YES];
    [self.searchBar resignFirstResponder];

    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{

    [self.searchBar resignFirstResponder];

}

- (void)handData{
             [SVProgressHUD show];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // time-consuming task
        dispatch_async(dispatch_get_main_queue(), ^{
          
            [SVProgressHUD showWithStatus:@"加载中..."];
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
            [SVProgressHUD setMinimumDismissTimeInterval:5];
            
        });
    });
    
    
    self.rank3 = nil;
  
    
    NSDictionary *dicOfHeader = @{@"Content-Type":@"application/x-www-form-urlencoded"};
    
    
    NSString *body = [@"query="stringByAppendingString:self.searchContect];
    
    [HWLNetworkTool POST:@"http://app.yanyue.cn/product/querysug" andBody:body andBodyStyle:HWLBodyString andHeader:dicOfHeader andResponse:HWLJSON andSuccessBlock:^(id result) {
       
        
        NSMutableArray *array = result[@"sug_list"];
        
        if (array.count == 0){
        
//            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"搜索烟品不存在!请重新输入!" message:nil preferredStyle:UIAlertControllerStyleAlert];
//            [alert addAction:[UIAlertAction actionWithTitle:@"好的,我重新输入" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//                //按钮触发的方法
//            }]];
//            
//            [self presentViewController:alert animated:YES completion:nil];
        
        }
        
        for (NSDictionary *dic in array) {
            
            [self.arrayOfSearchData addObject:dic[@"name"]];
            [self.arrayOfSearchDataId addObject:dic[@"id"]];
            
            
        }
        
              [self.tableView reloadData];
        
        [SVProgressHUD dismiss];
        
        
    } andFailureBlock:^(NSError *error) {
        
    }];
    
    
}


-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    
    self.searchContect = [searchText encodeToPercentEscapeString:searchText];
    
    [self.arrayOfSearchData removeAllObjects];
    
    [self handData];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if (self.arrayOfSearchData.count > 0) {
        return self.arrayOfSearchData.count;
    }
    if(self.rank3){
    
        return self.rank3.cigarettes.count;
    }
    return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (self.arrayOfSearchData.count > 0 ) {
        CigaretteTypeCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"CigaretteTypeCell"];
        
        cell.label.text = self.arrayOfSearchData[indexPath.row];
        
        return cell;
    }
    
    if (self.rank3) {
        
            RankTableViewThirdCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"RankTableViewThirdCell"];
            
            
            cell.name.text = self.rank3.cigarettes[indexPath.row].name;
            NSURL *url = [NSURL URLWithString:self.rank3.cigarettes[indexPath.row].photo];
            [cell.imageViewLift sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeholder"]];
            cell.catrameinput.text = self.rank3.cigarettes[indexPath.row].catrame;
            cell.priceinput.text = self.rank3.cigarettes[indexPath.row].price;
            NSInteger integer = self.rank3.cigarettes[indexPath.row].score;
            NSString *str = [NSString stringWithFormat:@"%ld",integer];
            cell.numberOfLike.text = str;
                return cell;
        
    }

    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (self.arrayOfSearchData) {
        
        self.requestid = self.arrayOfSearchDataId[0];
        [self handleData2];
    }
    
    if (self.rank3) {
        
        ProductDetailTableViewController *productDetail = [[ProductDetailTableViewController alloc]init];
        
        productDetail.productId = self.rank3.cigarettes[indexPath.row].uid;
        
        [self.navigationController pushViewController:productDetail animated:YES];
        
        
    }
    
   
    

}




- (void)handleData2{

    
    NSDictionary *dicOfHeader = @{@"Content-Type":@"application/x-www-form-urlencoded"};
    NSString *body = [[[@"ID="stringByAppendingString:self.requestid]stringByAppendingString:@"&query="]stringByAppendingString:self.searchContect];
   // NSLog(@"%@",body);
    
    [HWLNetworkTool POST:@"http://app.yanyue.cn/sort/search" andBody:body andBodyStyle:HWLBodyString andHeader:dicOfHeader andResponse:HWLJSON andSuccessBlock:^(id result) {
        
        self.rank3 = [Rank3 modelWithDic:result];
        
        [self.arrayOfSearchData removeAllObjects];
      
        [self.tableView reloadData];
        
        
    } andFailureBlock:^(NSError *error) {
        
    }];


}



-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (self.arrayOfSearchData.count > 0) {
        
        return 40;
    }
    if (self.rank3) {
        return 120;
        
    }
    return 0;
}



@end
